package com.zc.backend.controller;

import com.zc.backend.entity.Page;
import com.zc.backend.entity.Student;
import com.zc.backend.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@CrossOrigin
public class StudentController {

    @Autowired
    private StudentService studentService;


    @RequestMapping("/form")
    @ResponseBody
    public List<Student> goFrom(Page page){

        if (page.getPager()==null || page.getPageSize()==null){
            page.setPager(0);
            page.setPageSize(5);
        }
        List<Student> students = studentService.queryAll(page);
        return students;
    }

    @RequestMapping("/delete")
    public String delete( Integer id){
        System.out.println("id:"+id);
        studentService.delete(id);
        return "redirect:/form";
    }

    @RequestMapping("/goUpdate")
    @ResponseBody
    public Student goUpdate(Integer id){
        Student student = studentService.queryById(id);
        System.out.println(student);
        return student;
    }

    @RequestMapping("/update")
    public String update(Student student){
        System.out.println(student);
        studentService.update(student);
        return "redirect:/form";
    }

    @RequestMapping("/add")
    public String add(Student student){
        System.out.println(student);
        studentService.add(student);
        System.out.println("添加成功");
        return "redirect:/form";
    }
    @ResponseBody
    @RequestMapping("/count")
    public Page count(){
        Integer total = studentService.count();
        Page page = new Page();
        page.setTotal(total);
        return page;
    }

    @ResponseBody
    @RequestMapping("/queryByName")
    public List<Student> queryByName(Student student,Page page){
        if (page.getPager()==null || page.getPageSize()==null){
            page.setPager(0);
            page.setPageSize(5);
        }
        System.out.println(page);
        List<Student> students = studentService.queryByName(student.getName(),page);
        System.out.println(students);
        return students;
    }
    @ResponseBody
    @RequestMapping("/countByName")
    public Page countByName(String name){
        Integer total = studentService.countByName(name);
        Page page = new Page();
        page.setTotal(total);
        return page;
    }
}
